﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_popUpMateriales
    Inherits System.Web.UI.Page

    Dim CL As Logica.ModuloAdministracion.ControladorLogica
    Dim dataPresupuesto As New DataSetPresupuesto
    Dim dataPresupuestoCliente As New DataSetPresupuestoCliente


#Region "Datas"
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet
    Dim dtDatosMat As New DataTable
    Dim datasetMat As New DataSet
    Dim dtDatosInfoPres As New DataTable
    Dim datasetInfoPres As New DataSet
#End Region
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        CL = Logica.ModuloAdministracion.ControladorLogica.getInstance

        If Not Page.IsPostBack Then
            Me.panelMat.Visible = False
        End If

        cargarDatosPanelAddItem()
        Me.Loadpag()
        addAtributesToData()

        If Not Page.IsPostBack Then
            Dim dataTab As DataTable = Session("Material" + Request("pNumFila"))
            If Not dataTab Is Nothing Then
                Me.GridMaterial.DataSource = dataTab
                Me.GridMaterial.DataBind()
            Else
                Me.GridMaterial.DataBind()
            End If
        End If
       
    End Sub

#Region "Funciones"
    Public Sub cargarDatosPanelAddItem()
        Me.DropProv.Items.Clear()
        Me.DropFamilia.Items.Clear()

        Dim ArrayProveedor As New ArrayList
        Dim ArrayFamilia As New ArrayList

        Dim j As Integer
        ArrayProveedor = CL.ObtenerProveedor()
        ArrayFamilia = CL.ObtenerFamilia()

        For j = 0 To ArrayProveedor.Count - 1
            Dim ListaProv As New ListItem
            ListaProv.Text = DirectCast(ArrayProveedor.Item(j), Proveedor).Rznsocial
            ListaProv.Value = DirectCast(ArrayProveedor.Item(j), Proveedor).Rut
            Me.DropProv.Items.Add(ListaProv)
        Next
        For j = 0 To ArrayFamilia.Count - 1
            Dim ListaFam As New ListItem
            ListaFam.Text = DirectCast(ArrayFamilia.Item(j), Familia).Nombre
            ListaFam.Value = DirectCast(ArrayFamilia.Item(j), Familia).Id
            Me.DropFamilia.Items.Add(ListaFam)
        Next
    End Sub

    Private Sub Loadpag()
        Dim i As Integer
        Dim ArrayCliente As New ArrayList
        Dim arrayProveedores As New ArrayList

        ArrayCliente = CL.obtenerCliente()
        arrayProveedores = CL.ObtenerProveedor()

        If Not Page.IsPostBack Then
            Dim itemNuevo As New ListItem
            itemNuevo.Text = "Elija Proveedor"
            itemNuevo.Value = "Elija Proveedor"

            Me.DropProveedorMat.Items.Add(itemNuevo)

            For i = 0 To arrayProveedores.Count - 1

                Dim item As New ListItem
                item.Text = DirectCast(arrayProveedores.Item(i), Proveedor).Rznsocial
                item.Value = DirectCast(arrayProveedores.Item(i), Proveedor).Rut

                Me.DropProveedorMat.Items.Add(item)
            Next

        End If

        If Session("PresupuestoMat") Is Nothing Then
            Session("PresupuestoMat") = dtDatosMat
        Else
            dtDatosMat = DirectCast(Session("PresupuestoMat"), DataTable)
        End If

        If Not Page.IsPostBack Then
            Try
                dtDatosMat.Columns.Add(New DataColumn("ID"))
                dtDatosMat.Columns.Add(New DataColumn("ITEM"))
                dtDatosMat.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatosMat.Columns.Add(New DataColumn("DESCRIPCION"))
                dtDatosMat.Columns.Add(New DataColumn("VALORKG"))
                dtDatosMat.Columns.Add(New DataColumn("TOTNETO"))

                Me.GridMaterial.DataBind()
                Me.GridMaterial.DataSource = Me.dtDatosMat
                LlenarGridPresuAnterior()
            Catch
            End Try
        End If
        Me.GridMaterial.DataSource = Me.dtDatosMat
    End Sub

    Private Sub BuscarItemProveedor()
        Me.DropItemMatEspera.Items.Clear()
        Me.DropItemMatStock.Items.Clear()

        Dim ArrayMaterialProv As New ArrayList
        Dim arrayMaterial As New ArrayList
        Dim rutProv As String = Me.DropProveedorMat.SelectedValue

        arrayMaterial = CL.ObtenerMaterialStock(rutProv)
        ArrayMaterialProv = CL.obtenerMaterialProvEsperaCriterio(rutProv)

        For i As Integer = 0 To ArrayMaterialProv.Count - 1
            Dim item As New ListItem
            item.Value = DirectCast(ArrayMaterialProv.Item(i), MaterialPendiente).IdMaterialPendiente
            item.Text = DirectCast(ArrayMaterialProv.Item(i), MaterialPendiente).Nombre

            Me.DropItemMatEspera.Items.Add(item)
        Next

        For i As Integer = 0 To arrayMaterial.Count - 1
            Dim item As New ListItem
            item.Value = DirectCast(arrayMaterial.Item(i), Material).ID
            item.Text = DirectCast(arrayMaterial.Item(i), Material).Nombre

            Me.DropItemMatStock.Items.Add(item)
        Next

    End Sub

    Private Sub InsertarItemMaterial()
        Try
            Dim drDatos2 As DataRow = dtDatosMat.NewRow
            Dim idMps As String = ""
            idMps = CL.obtenerUltimoPresupuestoSubproyectoMaterial
            Dim neto As Integer = CInt(Me.TxTCantidadMat.Text) * CInt(eliminarFormatoNumero(Me.TxTValorMat.Text))
            Dim sitem As String = ""

            If Me.CBMateEsp.Checked Then
                sitem = Me.DropItemMatEspera.SelectedItem.Text
            Else
                If Me.CBMateStock.Checked Then
                    sitem = Me.DropItemMatStock.SelectedItem.Text
                End If
            End If

            drDatos2.Item("ID") = idMps
            drDatos2.Item("ITEM") = sitem
            drDatos2.Item("CANTIDAD") = CInt(Me.TxTCantidadMat.Text)
            drDatos2.Item("DESCRIPCION") = Me.TxTDescMat.Text
            drDatos2.Item("VALORKG") = eliminarFormatoNumero(Me.TxTValorMat.Text)
            drDatos2.Item("TOTNETO") = neto

            dtDatosMat.Rows.Add(drDatos2)
            Me.GridMaterial.DataSource = dtDatosMat
            Me.GridMaterial.DataBind()


        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub InsertarItemMaterialDB()
        If Me.TxTDescMat.Text <> "" And Me.TxTCantidadMat.Text <> "" And Me.TxTValorMat.Text <> "" Then
            If (Me.CBMateStock.Checked = True And Me.CBMateEsp.Checked = False) Or (Me.CBMateStock.Checked = False And Me.CBMateEsp.Checked = True) Then
                Dim mat As presupuestosubproyectomaterial


                Dim neto As Integer = CInt(Me.TxTCantidadMat.Text) * CInt(eliminarFormatoNumero(Me.TxTValorMat.Text))
                Dim iva As Integer = CInt(neto * 0.19)
                Dim fkpresu As Integer = CInt(Request("pNumFila").ToString)
                Dim fkmaterial As String = ""

                If Me.CBMateEsp.Checked Then
                    fkmaterial = Me.DropItemMatEspera.SelectedValue
                Else
                    If Me.CBMateStock.Checked Then
                        fkmaterial = Me.DropItemMatStock.SelectedValue
                    End If
                End If
                mat = New presupuestosubproyectomaterial(0, CInt(Me.TxTCantidadMat.Text), Me.TxTDescMat.Text, CInt(eliminarFormatoNumero(Me.TxTValorMat.Text)), fkpresu, fkmaterial, neto, iva)
                CL.insertarMaterialPresupuestoSubproyecto(mat, fkpresu)

                InsertarItemMaterial()

                Me.LimpiarMaterial()
                Me.GridMaterial.ForeColor = Drawing.Color.Blue
                Me.LabelAvisoMat.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAvisoMat.ForeColor = Drawing.Color.Red
                Me.LabelAvisoMat.Text = "debe seleccionar al menos un origen de material"
            End If

        Else
            Me.LabelAvisoMat.ForeColor = Drawing.Color.Red
            Me.LabelAvisoMat.Text = "Complete todos los datos"

        End If
    End Sub

    Private Sub LimpiarMaterial()
        Me.TxTCantidadMat.Text = String.Empty
        Me.TxTDescMat.Text = String.Empty
        Me.TxTValorMat.Text = String.Empty
    End Sub

    Private Sub deleteMatFromDB(ByVal id As Integer)
        CL.EliminarMaterialPresupuestoSubproyecto(id)
    End Sub

    Public Sub addAtributesToData()
        Me.TxTCantidadMat.Attributes.Add("onkeypress", "javascript:return ValidNum(event);")

        Me.TxTValorMat.Attributes.Add("onkeypress", "javascript:return ValidNum(event);")
        Me.TxTValorMat.Attributes.Add("OnKeyUp", "OnCurrencyValueKeyUp(this);")
        Me.TxTValorMat.Attributes.Add("Onblur", "addsimbol(this,1);")

    End Sub

    Public Function eliminarFormatoNumero(ByVal valor As String) As String
        valor = Replace(valor, "$", "")
        valor = Replace(valor, ",", "")
        valor = Replace(valor, "%", "")
        Return valor
    End Function

    Public Sub LlenarGridPresuAnterior()
        Try
            Dim fkPresuSubP As String = Request("pNumFila")
            Dim PresuSubPMate As ArrayList = CL.obtenerPresupuestoSubproyectoMaterial(fkPresuSubP)

            If PresuSubPMate.Count > 0 Then
                Me.panelMat.Visible = True
            End If

            Dim j As Integer

            For j = 0 To PresuSubPMate.Count - 1

                Dim drDatos2 As DataRow = dtDatosMat.NewRow

                Dim pspm As presupuestosubproyectomaterial = DirectCast(PresuSubPMate.Item(j), presupuestosubproyectomaterial)

                drDatos2.Item("ID") = pspm.id
                drDatos2.Item("ITEM") = pspm.fkmaterial
                drDatos2.Item("CANTIDAD") = pspm.cantidad
                drDatos2.Item("DESCRIPCION") = pspm.descripcion
                drDatos2.Item("VALORKG") = pspm.valorKg
                drDatos2.Item("TOTNETO") = pspm.neto
                dtDatosMat.Rows.Add(drDatos2)
            Next j
        Catch ex As Exception
        End Try

        Me.GridMaterial.DataSource = dtDatosMat
        Me.GridMaterial.DataBind()
    End Sub

#End Region

#Region "eventos"

    Sub GridMaterial_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Handles GridMaterial.RowDeleting
        Dim dt As DataTable = CType(Session("PresupuestoMat"), DataTable)
        deleteMatFromDB(CInt(dt.Rows(e.RowIndex).Item(0)))
        dt.Rows(e.RowIndex).Delete()
        GridMaterial.DataSource = dt
        GridMaterial.DataBind()
    End Sub

#End Region


#Region "Botones"

    Protected Sub BtnIngresarMat_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnIngresarMat.Click
        Me.panelMat.Visible = True
        InsertarItemMaterialDB()
    End Sub

    Protected Sub BtnLimpMat_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnLimpMat.Click
        Me.LimpiarMaterial()
    End Sub
#End Region


    Protected Sub CBMateEspera_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CBMateEsp.CheckedChanged
        If Me.CBMateEsp.Checked = True Then
            Me.DropItemMatStock.Enabled = False
            Me.DropItemMatEspera.Enabled = True
            Me.CBMateStock.Checked = False
        Else
            Me.DropItemMatStock.Enabled = True
            Me.DropItemMatEspera.Enabled = False
        End If
    End Sub

    Protected Sub CBMateStock_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CBMateStock.CheckedChanged
        If Me.CBMateStock.Checked = True Then
            Me.DropItemMatEspera.Enabled = False
            Me.DropItemMatStock.Enabled = True
            Me.CBMateEsp.Checked = False
        Else
            Me.DropItemMatEspera.Enabled = True
            Me.DropItemMatStock.Enabled = False
        End If
    End Sub

  
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        IngresarNuevoItem()
    End Sub
    Private Sub IngresarNuevoItem()

        Dim nombre As String = Me.Txtnom.Text
        Dim descripcionFormal As String = Me.TxtDescFormal.Text
        Dim descripcionInformal As String = Me.TxTDescInformal.Text
        Dim stockMinimo As String = Me.TxTStockMinimo.Text
        Dim idFamilia As String = Me.DropFamilia.SelectedValue

        If descripcionFormal <> "" And descripcionInformal <> "" And stockMinimo <> "" Then
            Dim nuevoMaterial As New Material()
            nuevoMaterial.Nombre = nombre
            nuevoMaterial.DescripcionFormal = descripcionFormal
            nuevoMaterial.DescripcioninFormal = descripcionInformal
            nuevoMaterial.STOCKMINIMO = stockMinimo
            nuevoMaterial.RefFAmilia = idFamilia
            CL.InsertarMaterialTemporal(nuevoMaterial)
            clean()
            Me.Mensaje("El material a sido ingresado con exito")
        Else
            Me.Mensaje("Dato Faltante, rellene todos los campos")
        End If

    End Sub
    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub


    Private Sub clean()
        Me.Txtnom.Text = ""
        Me.TxtDescFormal.Text = ""
        Me.TxTDescInformal.Text = ""
        Me.Txtnom.Text = ""
        Me.TxTStockMinimo.Text = ""
    End Sub

    Protected Sub DropProveedorMat_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropProveedorMat.SelectedIndexChanged
        BuscarItemProveedor()
    End Sub
End Class
